package com.niit.mobileDevide.numofapp;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class NumOfAppMapper extends Mapper<LongWritable, Text, Text, NumOfAppBean> {

    private static final int AGE_INDEX = 8; // 年龄索引
    private static final int NUM_APPS_INSTALLED_INDEX = 6; // 已安装应用数量索引

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length < 9) { // 确保至少有9个字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 解析年龄
            int age = Integer.parseInt(columns[AGE_INDEX].trim());

            // 提取已安装应用数量
            int numAppsInstalled = Integer.parseInt(columns[NUM_APPS_INSTALLED_INDEX].trim());

            // 根据年龄确定分组
            String ageGroup;
            if (age >= 0 && age <= 25) {
                ageGroup = "0-25";
            } else if (age > 25) {
                ageGroup = "25+";
            } else {
                System.err.println("Unexpected age value: " + age + ". Skipping line.");
                return;
            }

            // 创建 NumOfAppBean 对象
            NumOfAppBean bean = new NumOfAppBean(numAppsInstalled);

            // 写入键值对 (年龄分组, NumOfAppBean)
            context.write(new Text(ageGroup), bean);

        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}